#include "WinApp.h"
#include "PEMath.h"
#include "InputManager.h"

using namespace PracEng;
#define KEY_DOWN(VK_CODE) ( (GetAsyncKeyState(VK_CODE) & 0x8000) ? 1 : 0 )

InputManager::InputManager()
{
	ZeroMemory(KeyStates, sizeof(EKEY_STATE) * 256);
}

void InputManager::UpdateKeyStatesDown(WPARAM wparam, LPARAM lparam)
{
	UINT KeyCode = wparam;

	EKEY_STATE bOldKeyState = KeyStates[KeyCode];
	if (bOldKeyState == EKEYSTATE_UnPress)
		KeyStates[KeyCode] = EKEYSTATE_Pressed;
	else if (bOldKeyState == EKEYSTATE_Pressed)
		KeyStates[KeyCode] = EKEYSTATE_Repeat;

}

void InputManager::UpdateKeyStatesUp(WPARAM wparam, LPARAM lparam)
{
	UINT KeyCode = wparam;

	KeyStates[KeyCode] = EKEYSTATE_UnPress;

}

void InputManager::UpdateMouseDown(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	if ( uMsg == WM_LBUTTONDBLCLK || uMsg == WM_LBUTTONDOWN)
	{
		bLeftMouseBtnDown = true;
		SetCapture(hWnd);
		GetCursorPos(&m_ptLastMousePos);
	}
}

void InputManager::UpdateMouseUp(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	if (uMsg == WM_LBUTTONUP)
	{
		bLeftMouseBtnDown = false;
		ReleaseCapture();
	}
}

void InputManager::OnReleaseCapture()
{
	bLeftMouseBtnDown = false;
}

void InputManager::ProcessInput(float DeltaTime)
{
	//update key
	PEVector3 MoveDir;
	if (KeyStates[VK_LEFT] == EKEYSTATE_Repeat || KeyStates[VK_LEFT] == EKEYSTATE_Pressed)
	{
		MoveDir.x -= DeltaTime * 10;
	}
	if (KeyStates[VK_RIGHT] == EKEYSTATE_Repeat || KeyStates[VK_RIGHT] == EKEYSTATE_Pressed)
	{
		MoveDir.x += DeltaTime * 10;
	}
	if (KeyStates[VK_UP] == EKEYSTATE_Repeat || KeyStates[VK_UP] == EKEYSTATE_Pressed)
	{
		MoveDir.z += DeltaTime * 10;
	}
	if (KeyStates[VK_DOWN] == EKEYSTATE_Repeat || KeyStates[VK_DOWN] == EKEYSTATE_Pressed)
	{
		MoveDir.z -= DeltaTime * 10;
	}

	WinApp::GetApp()->GetCamera()->Move(MoveDir);

	// update mouse
	POINT ptMouseDelta;
	POINT ptCurMousePos;

	GetCursorPos(&ptCurMousePos);

	ptMouseDelta.x = ptCurMousePos.x - m_ptLastMousePos.x;
	ptMouseDelta.y = ptCurMousePos.y - m_ptLastMousePos.y;

	m_ptLastMousePos = ptCurMousePos;

	float fPercentOfNew = 0.5f;
	float fPercentOfOld = 1.0f - fPercentOfNew;
	m_MouseDelta.X = m_MouseDelta.X * fPercentOfOld + ptMouseDelta.x * fPercentOfNew;
	m_MouseDelta.Y = m_MouseDelta.Y * fPercentOfOld + ptMouseDelta.y * fPercentOfNew;

	m_MouseDelta.X *= 0.005f;
	m_MouseDelta.Y *= 0.003f;
	if (bLeftMouseBtnDown)
	{
		WinApp::GetApp()->GetCamera()->Rotate(m_MouseDelta);
	}

	//other logic
	if (KeyStates[0x47] == EKEYSTATE_Pressed)
		WinApp::GetApp()->GetSceneMgr()->bShowGbuffer = !WinApp::GetApp()->GetSceneMgr()->bShowGbuffer;

	if (KeyStates[0x56] == EKEYSTATE_Pressed)
		WinApp::GetApp()->GetSceneMgr()->bShowLightVolume = !WinApp::GetApp()->GetSceneMgr()->bShowLightVolume;
}

void InputManager::Tick(float DeltaTime)
{
	ProcessInput(DeltaTime);
}